/*
 * Powered By [pkuWx]
 * Web Site: http://www.wuxi.ss.pku.edu.cn
 * Since 2015 - 2015
 */

package cn.edu.pku.wxlib.adminuser.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javacommon.base.BaseRestSpringController;
import javacommon.page.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.pku.wxlib.admintorole.service.AdmintoroleManager;
import cn.edu.pku.wxlib.adminuser.model.Adminuser;
import cn.edu.pku.wxlib.adminuser.service.AdminuserManager;
import cn.edu.pku.wxlib.adminuser.vo.query.AdminuserQuery;
import cn.edu.pku.wxlib.common.authority.Login;
import cn.edu.pku.wxlib.role.model.Role;
import cn.edu.pku.wxlib.vo.sessionmodel.SessionUser;
import cn.org.rapid_framework.web.scope.Flash;

/**
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/adminuser")
public class AdminuserController extends BaseRestSpringController<Adminuser, java.lang.Integer> {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	private final String LIST_ACTION = "redirect:/adminuser";

	private AdminuserManager adminuserManager;

	private AdmintoroleManager atrManager;
	public void setAdminuserManager(AdminuserManager manager) {
		this.adminuserManager = manager;
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}

	/** 增加了@ModelAttribute的方法可以在本controller方法调用前执行,可以存放一些共享变量,如枚举值,或是一些初始化操作 */
	@ModelAttribute
	public void init(ModelMap model) {
	}

	/**
	 * 后台系统登陆
	 * 
	 * @param model
	 * @param loginInfo
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(ModelMap model, @Valid AdminuserQuery loginInfo, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String redirectUrl = request.getParameter("redirectUrl");
		if (redirectUrl != null && !("").equals(redirectUrl))
			redirectUrl = java.net.URLDecoder.decode(redirectUrl, "utf-8");

		String loginAccout = loginInfo.getAdminName();
		String loginPsw = loginInfo.getPassword();
		// loginInfo.setPassword(LibUtil.md5(loginPsw));

		if (loginAccout == null || loginAccout.equals("")) {
			return "redirect:/login.jsp?errormsg=-1";
		}
		if (loginPsw == null || loginPsw.equals("")) {
			return "redirect:/login.jsp?errormsg=-1";
		}

		List<Adminuser> result = adminuserManager.findAllByQuery(loginInfo);

		if (result.size() == 0) {
			return "redirect:/login.jsp?errormsg=-1";
		} else if (result.size() > 1) {
			return "redirect:/login.jsp?errormsg=-1";
		} else {
			Adminuser adminuser = result.get(0);
			SessionUser sessionUser = new SessionUser();
			sessionUser.setUserId(adminuser.getAdminId());
			sessionUser.setUserName(adminuser.getAdminName());
			sessionUser.setName(adminuser.getName());
			sessionUser.setGender(adminuser.getGender());

			HttpSession session = request.getSession();
			session.setAttribute("login", sessionUser);
			System.out.println(sessionUser.getGender());
			if (redirectUrl != null && !("").equals(redirectUrl)) { // 如果存在要跳转的页面
				return "redirect:" + redirectUrl;
			} else {
				return "redirect:/student";
			}
		}
	}

	/**
	 * 后台系统登出
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/logout")
	public String logout(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		session.setAttribute("login", null);
		return "redirect:/";
	}

	/** 列表 */
	@Login
	@RequestMapping
	public String index(ModelMap model, AdminuserQuery query, HttpServletRequest request,
			HttpServletResponse response) {
		Page page = this.adminuserManager.findPage(query);
		//装入用户的角色
        for (Adminuser user : ((List<Adminuser>) page.getResult()) ) {
        	List<Role> roleList = adminuserManager.listRoleByAdmin(user.getAdminId());
            user.setRolelist(roleList);
        }
		model.addAllAttributes(toModelMap(page, query));
		return "/adminuser/index";
	}

	/** 显示 */
	@Login
	@RequestMapping(value = "/{id}")
	public String show(ModelMap model, @PathVariable java.lang.Integer id) throws Exception {
		Adminuser adminuser = (Adminuser) adminuserManager.getById(id);
		model.addAttribute("adminuser", adminuser);
		return "/adminuser/show";
	}

	/** 进入新增 */
	@Login
	@RequestMapping(value = "/new")
	public String _new(ModelMap model, Adminuser adminuser, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		model.addAttribute("adminuser", adminuser);
		return "/adminuser/new";
	}

	/** 保存新增 */
	@Login @RequestMapping(method=RequestMethod.POST)
	public String create(ModelMap model,@Valid Adminuser adminuser,BindingResult errors,HttpServletRequest request,HttpServletResponse response) throws Exception {	
		//验证是用户名是否重复
		if(adminuserManager.checkExist("adminName",adminuser.getAdminName())&!("").equals(adminuser.getAdminName()))
			errors.addError(new FieldError("adminuser","adminName","用户名已存在"));
		if(errors.hasErrors()) {
			return  "/adminuser/new";
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		adminuser.setCreateTimeString(df.format(new Date()));
		adminuserManager.save(adminuser);
		Flash.current().success(CREATED_SUCCESS);
		return LIST_ACTION;
	}

	/** 编辑 */
	@Login
	@RequestMapping(value = "/{id}/edit")
	public String edit(ModelMap model, @PathVariable java.lang.Integer id) throws Exception {
		Adminuser adminuser = (Adminuser) adminuserManager.getById(id);
		model.addAttribute("adminuser", adminuser);
		return "/adminuser/edit";
	}

	/** 保存更新 */
	@Login
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	public String update(ModelMap model, @PathVariable java.lang.Integer id, @Valid Adminuser adminuser,
			BindingResult errors, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (errors.hasErrors()) {
			return "/adminuser/edit";
		}

		adminuserManager.update(adminuser);
		Flash.current().success(UPDATE_SUCCESS);
		return LIST_ACTION;
	}

	/** 进入个人信息的更改 ，超链接,GET方式提交*/
	@Login
	@RequestMapping(value = "/{id}/personaledit",method = RequestMethod.GET)
	public String modify(ModelMap model, @PathVariable java.lang.Integer id) throws Exception {
		Adminuser adminuser = (Adminuser) adminuserManager.getById(id);
		model.addAttribute("adminuser", adminuser);
		return "/adminuser/personaledit";
	}
	
	/** 保存个人信息的更改，form:form表单，PUT提交方式 */
	@Login
	@RequestMapping(value = "/{id}/save", method = RequestMethod.PUT)
	public String saveModify(ModelMap model, @PathVariable java.lang.Integer id, @Valid Adminuser adminuser,
			BindingResult errors, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (errors.hasErrors()) {
			return "/adminuser/personaledit";
		}
		adminuserManager.update(adminuser);
//		Flash.current().success(UPDATE_SUCCESS);
		return "/adminuser/personalcenter";
	}
	
	/** 删除 */
	@Login
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String delete(ModelMap model, @PathVariable java.lang.Integer id) {
		adminuserManager.removeById(id);
		Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}

	/** 批量删除 */
	@Login
	@RequestMapping(method = RequestMethod.DELETE)
	public String batchDelete(ModelMap model, @RequestParam("items") java.lang.Integer[] items) {
		for (int i = 0; i < items.length; i++) {
			adminuserManager.removeById(items[i]);
		}
		Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}
	
	@Login
	@RequestMapping(value = "/personalcenter", method = RequestMethod.GET)
	public String PersonnalCenter(ModelMap model, @Valid AdminuserQuery adminuserQuery,HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer adminuserId=adminuserQuery.getAdminId();
		List<Adminuser> resultMap=adminuserManager.findById(adminuserId);
		Adminuser adminuser=resultMap.get(0);
		HttpSession session = request.getSession();
		session.setAttribute("adminuser", adminuser);
		return "/adminuser/personalcenter";
	}
	
	//改变用户状态
	@Login @RequestMapping(value="/{id}&{state}/changeState")
	public String changeState(@PathVariable Integer id,@PathVariable Integer state){
		Integer changeState = state;
		Integer adminId = id;
		adminuserManager.changeState("adminId", adminId, "state", changeState);
		return LIST_ACTION;
	} 
	
	//根据用户ID查找没有分配的角色
	@Login @RequestMapping(value="/{id}/listUnknownRoleByAdmin")
	public @ResponseBody Map<String, Object> listUnknownRoleByAdmin(AdminuserQuery query,@PathVariable Integer id,ModelMap model, HttpServletRequest request, HttpServletResponse response){
		Integer adminId = id;
//		PageRequest<Map> pageRequest = new PageRequest();
//		bindPageRequest(request,pageRequest,DEFAULT_SORT_COLUMNS);
//		Map params = new HashMap();
//		params.put("adminId", adminId);
//		BeanUtilsBean beanUtils = new BeanUtilsBean();
//		beanUtils.copyProperties(pageRequest, params);
		query.setAdminId(adminId);
		Page page = this.adminuserManager.listUnknownRoleByAdmin(query);
//		saveIntoModelMap("assignRolesForm",page,query,model);
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("data", page.getResult());
		json.put("currentPage", page.getThisPageNumber());
		json.put("pageNum", page.getPageSize());
		json.put("total", page.getTotalCount());
		return json;
	}
	
	//根据用户ID查找已分配的角色
	@Login @RequestMapping(value="/{id}/listRoleByAdmin")
	public @ResponseBody Map<String, Object> listRoleByAdmin(AdminuserQuery query,@PathVariable Integer id,ModelMap model, HttpServletRequest request, HttpServletResponse response){
		Integer adminId = id;
		query.setAdminId(adminId);
		Page page = this.adminuserManager.listRoleByAdmin(query);
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("data", page.getResult());
		json.put("currentPage", page.getThisPageNumber());
		json.put("pageNum", page.getPageSize());
		json.put("total", page.getTotalCount());
		return json;
		}
	
	//分配角色
	@Login @RequestMapping(value="/{id}/assignRoles")
	public String assignRoles(ModelMap model,@RequestParam("roleItems") java.lang.Integer[] roleItems,@PathVariable Integer id){
		Integer adminId = id;
		adminuserManager.assignRoles(adminId,roleItems);
		return LIST_ACTION;
	}
	
	//删除已分配的角色
	@Login @RequestMapping(value="/{id}/deleteRoles")
	public String deleteRoles(ModelMap model,@RequestParam("roleItems") java.lang.Integer[] roleItems,@PathVariable Integer id){
		Integer adminId = id;
		adminuserManager.deleteRoles(adminId,roleItems);
		return LIST_ACTION;
	}
}
	
